﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mail;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

public class MailKitEmailService
{
    public string SmtpServer { get; set; }
    public int SmtpPort { get; set; }
    public bool EnableSsl { get; set; }
    public string Username { get; set; } // 通常为发件人邮箱地址
    public string Password { get; set; }

    public MailKitEmailService(string server, int port, bool enableSsl, string username, string password)
    {
        SmtpServer = server;
        SmtpPort = port;
        EnableSsl = enableSsl;
        Username = username;
        Password = password;
    }

    public async Task SendEmailAsync(string from, string to, string subject, string body, bool isHtml = false, List<(Stream stream, string fileName)> attachments = null)
    {
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("QQ左手", from)); // 发送人
        message.To.Add(new MailboxAddress("曾凌波", to)); // 收件人
        message.Subject = subject;

        var bodyBuilder = new BodyBuilder
        {
            TextBody = body, // 如果不是Html邮件，使用TextBody
            HtmlBody = body // 如果是Html邮件，使用HtmlBody
        };

        if (isHtml)
        {
            bodyBuilder.HtmlBody = body;
        }

        // 添加附件
        if (attachments != null)
        {
            foreach (var attachment in attachments)
            {
                bodyBuilder.Attachments.Add(attachment.fileName, attachment.stream);
            }
        }

        message.Body = bodyBuilder.ToMessageBody();

        try
        {
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                await client.ConnectAsync(SmtpServer, SmtpPort, SecureSocketOptions.StartTls);
                await client.AuthenticateAsync(Username, Password);
                await client.SendAsync(message);
                await client.DisconnectAsync(true);
            }
        }
        catch (Exception ex)
        {
            // 处理异常，获取错误信息
            Console.WriteLine("发送邮件失败: " + ex.Message);
        }
    }
}